package zl.osimall.common.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zl.osimall.common.exception.SteduException;
import zl.osimall.common.mapper.AdminMapper;
import zl.osimall.common.service.AdminService;
import zl.osimall.common.utils.MD5Util;
import zl.osimall.common.bean.Admin;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Admin login(String username, String password) throws SteduException {
        Admin admin = adminMapper.selectByUsername(username);
        if(admin == null){
            throw new SteduException("用户不存在，无法登录");
        }
        String md5Pwd = MD5Util.getMD5(password + admin.getSalt());
        if (!admin.getPassword().equals(md5Pwd)){
            throw new SteduException("密码错误，无法登录");
        }
        return admin;
    }

    @Override
    public Admin update(Admin newAdmin) throws SteduException {
        Admin admin = adminMapper.selectByUsername(newAdmin.getUsername());
        if(admin == null){
            throw new SteduException("用户不存在，无法修改");
        }
        String md5Pwd = MD5Util.getMD5(newAdmin.getPassword() + admin.getSalt());
        if (!admin.getPassword().equals(md5Pwd)){
            throw new SteduException("密码错误，无法登录");
        }
        newAdmin.setPassword(MD5Util.getMD5(newAdmin.getNewPassword() + admin.getSalt()));
        if(adminMapper.update(newAdmin) != 1){
            throw new SteduException("修改失败");
        }
        return newAdmin;
    }
}
